package com.myway.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myway.core.common.JsonUtils;
import com.myway.core.util.HttpClientUtil;
import com.myway.dao.FlyErrPriceMapper;
import com.myway.dto.domain.TotalFlyPrice;
import com.myway.dto.ibe_param.FlightParam;
import com.myway.dto.ibe_param.TaxPrice;
import com.myway.dto.ibe_param.TicketPrice;
import com.myway.dto.util.BigDecimalUtils;
import com.myway.pojo.FlyErrPrice;
import com.myway.pojo.FlyErrPriceWithBLOBs;
import com.myway.pojo.FlyPassenge;
import com.myway.service.CountPriceService;
import com.myway.utils.DateUtil;
import com.myway.utils.eamil.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class CountPriceServiceImpl implements CountPriceService{

    private  final  double childrenAmountRate=0.6;
    private  final  double babyrAmountRate=0.1;

    @Autowired
    private FlyErrPriceMapper flyErrPriceMapper;

    /**
     * 根据单仓位计算价格
     * @param param
     * @return
     */
    @Override
    public Map findCabinTypePrice(FlightParam param) {
//        TicketPrice  ticketPrice=null;
        String  jsonString=JSON.toJSONString(param);
        String sagementList = HttpClientUtil.doPostJson("http://47.75.92.162:49001/price/fare", jsonString);
            //String sagementList = HttpClientUtil.doPostJson("http://172.17.19.23:8030/av/flights", JSON.toJSONString(list));
            //单仓等返回票价对象
        List<TicketPrice> ticketPrices = JSON.parseArray(sagementList, TicketPrice.class);
        Map map = new HashMap();
        map=countCabinTypePrice(ticketPrices);
        return map;
    }

    /**
     * 多航段组合舱位计算票价
     * @param params
     * @param
     * @return
     */
    public Map findCabinTypePrice(List<FlightParam> params) {
//        TicketPrice  ticketPrice=null;
         String  jsonString=JSON.toJSONString(params);
         //正式
         String sagementList = HttpClientUtil.doPostJson("http://47.75.92.162:49001/price/fare", jsonString);
         //測試
        //String sagementList = HttpClientUtil.doPostJson("http://127.0.0.1:8081/price/fare", jsonString);
        //单仓等返回票价对象
        List<TicketPrice> ticketPrices = JSON.parseArray(sagementList, TicketPrice.class);
        Map map = new HashMap();
        map=countCabinTypePrice(ticketPrices);
        String status = String.valueOf(map.get("priceStatus"));
        System.out.println(ticketPrices.get(0).getRequestStr());
        if (status.equals("false")){
            for (TicketPrice ticketPrice:ticketPrices) {
                if(ticketPrice.getFuncCtrlChar()!=3){
                    FlightParam param = params.get(0);
                    FlyErrPrice flyErrPrice = new FlyErrPriceWithBLOBs();
                    flyErrPrice.setTicketType(param.getTravlType());
                    flyErrPrice.setDepCode(param.getOrgCity());
                    flyErrPrice.setArrCode(param.getDstCity());
                    flyErrPrice.setFlightNo(param.getFlightNo());
                    flyErrPrice.setCabinClass(param.getCabinCode());
                    flyErrPrice.setDepTime(DateUtil.formatStrToDate(param.getFlightDate()));
                    FlyErrPrice result = flyErrPriceMapper.findByInfo(flyErrPrice);
                    if(result == null){
                        FlyErrPriceWithBLOBs flyErrPriceWithBLOBs = (FlyErrPriceWithBLOBs)flyErrPrice;
                        flyErrPriceWithBLOBs.setErrPrice(BigDecimal.valueOf(ticketPrice.getTotalFareAmount()));
                        flyErrPriceWithBLOBs.setRequestStr(ticketPrice.getRequestStr());
                        flyErrPriceWithBLOBs.setResponseStr(ticketPrice.getResponseStr());
                        flyErrPriceWithBLOBs.setLogTime(new Date());
                        flyErrPriceMapper.insert(flyErrPriceWithBLOBs);
                        String context = "<b>TravlType：</b>"+param.getTravlType()+"<br/><b>Trip：</b>"+param.getOrgCity()+" -- "+param.getDstCity()+"<br/><b>Flight No：</b>MJ"+param.getFlightNo()+"<br/><b>Cabin Class：</b>"+param.getCabinCode()+"<br/><b>Flight Date/Time：</b>"+param.getFlightDate()+"<br/><br/><b>pricingRequest</b><br/>"+JsonUtils.jsonToHtml(ticketPrice.getRequestStr())+"<br/><b>pricingResponse</b><br/>"+JsonUtils.jsonToHtml(ticketPrice.getResponseStr());
                        EmailUtils.sendHtmlEmail("juliet.zhao@mywayairlines.com","Warning Price Result",context,null);
                    }
                    break;
                }
            }
        }
        return map;
    }

    public List<TicketPrice> findCabinTicketPrice(List<FlightParam> params) {
//        TicketPrice  ticketPrice=null;
        String jsonString="";
        jsonString=JSON.toJSONString(params);
        String sagementList = HttpClientUtil.doPostJson("http://47.75.92.162:49001/price/fare", jsonString);
        //String sagementList = HttpClientUtil.doPostJson("http://172.17.19.23:8030/av/flights", JSON.toJSONString(list));
        //单仓等返回票价对象
        List<TicketPrice> ticketPrices = JSON.parseArray(sagementList, TicketPrice.class);
        return ticketPrices;
    }

    /**
     * 计算舱位票价
     * @param ticketPrices
     * @return
     */
    public Map countCabinTypePrice(List<TicketPrice> ticketPrices){
        Map map = new HashMap();
        //税费集合
        //List<TaxPrice> taxPrices = ticketPrice.getTaxPrices();
        List<TaxPrice> newtax = new ArrayList<TaxPrice>();
        TaxPrice tx = new TaxPrice();
        //总税费
        double taxP = BigDecimalUtils.getAddAmount(ticketPrices.get(0).getTotalFareAmount() - ticketPrices.get(0).getEquivFareAmount());
        tx.setAmount(taxP);
        newtax.add(tx);
        ticketPrices.get(0).setTaxPrices(newtax);
        //新的机票价格
        //TicketPrice newPriceList= new TicketPrice();
        //如果原票价的货币和税费货币代码不一致。则需要对其进行汇率转换。将税费货币转换成原票价的货币
/*        if(!ticketPrice.getBaseFareCurrencyCode().equals(taxPrices.get(0).getCurrencyCode())){
            for (TaxPrice list: taxPrices){
                TaxPrice tx = new TaxPrice();
                double divideAmount = BigDecimalUtils.getDivideAmount(list.getAmount(), ticketPrice.getBaseFareRate());
                tx.setAmount(divideAmount);
                tx.setTaxName(list.getTaxName());
                newtax.add(tx);
            }
            //将session中的值赋值给新的价格对象
            newPriceList=(TicketPrice)ticketPrice.clone();
            newPriceList.setTaxPrices(newtax);
        }else{
            newPriceList=ticketPrice;
        }*/

        //double adultTaxAmount =ticketPrice.getBaseFareAmount();

        TotalFlyPrice totalFlyPrice = new TotalFlyPrice();
        //成人的机票总价(含税)
        totalFlyPrice.setAdultAmount(BigDecimalUtils.getAddAmount(ticketPrices.get(0).getTotalFareAmount()));
        //成人的机票总价(不含税)
        totalFlyPrice.setAdultNotTaxAmount(BigDecimalUtils.getAddAmount(ticketPrices.get(0).getEquivFareAmount()));
        //儿童的机票总价(含税)
        totalFlyPrice.setChildrenAmount(BigDecimalUtils.getAddAmount(ticketPrices.get(1).getTotalFareAmount()));
        //儿童的机票总价(不含税)
        totalFlyPrice.setChildrenNotTaxAmount(BigDecimalUtils.getAddAmount(ticketPrices.get(1).getEquivFareAmount()));
        //婴儿的机票总价(含税)
        totalFlyPrice.setBabayAmount(BigDecimalUtils.getAddAmount(ticketPrices.get(2).getTotalFareAmount()));
        //婴儿的机票总价(不含税)
        totalFlyPrice.setBabayNotTaxAmount(BigDecimalUtils.getAddAmount(ticketPrices.get(2).getEquivFareAmount()));
        //成人机税总价格
        totalFlyPrice.setAdultTaxAmount(BigDecimalUtils.getAddAmount(taxP));
        map.put("totalFlyPrice",totalFlyPrice);
        map.put("cabinTypePrice",ticketPrices);
        map.put("taxPrices",ticketPrices.get(0).getTaxPrices());
        return map;
    }

    @Override
    public Map countAmount(String passageList, String taxList, TotalFlyPrice totalFlyPrice) {
        List<FlyPassenge> passgae = JSONObject.parseArray(passageList, FlyPassenge.class);
        List<Double> tax = JSONObject.parseArray(taxList,Double.class);
        //所有乘客机票税费总价
        double PassageTotal=0.00;
        //单个(单个x人数)税费总和
        double[] totalTax=new double[tax.size()];
        //所有乘客机票总价
        double totalFly=0.00;
        //临时税费总和
        double taxTotal=0.00;
        for (int i=0;i< tax.size();i++){
            taxTotal+= 0;
            totalTax[i]=BigDecimalUtils.getAddAmount(tax.get(i)*passgae.size());
        }

        for (int i=0;i<passgae.size();i++){
            if(passgae.get(i).getPassageType().equals("1")){
                PassageTotal+=totalFlyPrice.getAdultAmount();
                totalFly+=totalFlyPrice.getAdultAmount();
            }
            if(passgae.get(i).getPassageType().equals("2")){
                PassageTotal+=totalFlyPrice.getChildrenAmount();
                totalFly+=totalFlyPrice.getChildrenAmount();
            }
            if(passgae.get(i).getPassageType().equals("3")){
                PassageTotal+=totalFlyPrice.getBabayAmount();
                totalFly+=totalFlyPrice.getBabayAmount();
            }
        }
        Map map= new HashMap();
        //所有乘客机票总价
        map.put("PassageTotal",PassageTotal);
        //税费数组
        map.put("totalTax",totalTax);
        //所有旅客机票总价
        map.put("totalFly",totalFly);
        return map;
    }


}
